package com.huawei.hms.framework.network.restclient.dnkeeper;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import com.huawei.hms.framework.common.CheckParamUtils;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.common.PLSharedPreferences;
import com.huawei.hms.framework.network.grs.GrsApi;
import com.huawei.hms.framework.network.restclient.hwhttp.HttpClientGlobalInstance;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DNManager;
import com.huawei.hms.framework.network.restclient.hwhttp.dns.DnsResult;
import com.huawei.hms.framework.network.util.ContextUtil;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DNKeeperManager {
    private static final int PoolSize = 8;
    private static final String TAG = "DNKeeperManager";
    private static final String URL_SPLIT = ":";
    private static String defaultDomain;
    @SuppressLint({"StaticFieldLeak"})
    private static DNKeeperManager instance = new DNKeeperManager();
    private Context context;
    private String ip;
    private volatile boolean isInit = false;
    private final Object lock = new Object();
    private PLSharedPreferences preferences;
    private volatile int requestIntervalFailed = 60000;
    private ConcurrentHashMap<String, RequestRecord> requestRecordHashMap = new ConcurrentHashMap();
    private ExecutorService taskExecutor = new ThreadPoolExecutor(8, 16, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new DefaultThreadFactory());
    private int timeout;

    static class DefaultThreadFactory implements ThreadFactory {
        private final String name;

        private DefaultThreadFactory() {
            this.name = "networkkit_dnkeeper";
        }

        public Thread newThread(Runnable runnable) {
            return new Thread(runnable, "networkkit_dnkeeper");
        }
    }

    private DNKeeperManager() {
    }

    public static DNKeeperManager getInstance() {
        return instance;
    }

    public void setRequestIntervalFailed(int i) {
        if (i < 30000 || i >= 600000) {
            Logger.w(TAG, "the setRequestIntervalFailed, set to default:" + i);
        } else {
            this.requestIntervalFailed = i;
        }
    }

    public void init(Context context) {
        init(context, 10000);
    }

    public void init(final Context context, int i) {
        CheckParamUtils.checkNotNull(context, "context == null");
        this.context = context.getApplicationContext();
        HttpClientGlobalInstance.getInstance().init(this.context);
        try {
            defaultDomain = this.context.getString(R.string.networkkit_dnkeeper_domain);
        } catch (Throwable th) {
            Logger.v(TAG, "DEFAULT_DOMAIN_NAME failed: " + th);
        }
        Logger.v(TAG, "defaultDomain " + defaultDomain);
        if (i < 0 || i > 10000) {
            Logger.w(TAG, "maybe you need set a time between 0-10000");
            i = 10000;
        }
        this.timeout = i;
        if (!this.isInit) {
            this.isInit = true;
            this.taskExecutor.submit(new Runnable() {
                public void run() {
                    DNKeeperManager.this.preferences = new PLSharedPreferences(context.getApplicationContext(), DNKeeperConfig.NAME_DNS);
                    DNManager.getInstance().init(context, DefaultDNKeeper.getInstance(context));
                    String domainName = DNKeeperManager.this.getDomainName();
                    if (TextUtils.isEmpty(domainName)) {
                        Logger.w(DNKeeperManager.TAG, "not found dnkeeper domain, must check");
                        return;
                    }
                    boolean checkDNKeeperIP = DNKeeperUtil.checkDNKeeperIP(DNKeeperManager.this.preferences, domainName);
                    Logger.v(DNKeeperManager.TAG, "checkDNKeeperIP " + checkDNKeeperIP);
                    if (checkDNKeeperIP) {
                        DNKeeperManager.this.submitRequest(new RequestHost(domainName), domainName);
                    }
                }
            });
        }
    }

    public boolean isInit() {
        return this.isInit;
    }

    public String getHost(String str) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        Uri parse = Uri.parse(str);
        if (parse.getPort() == -1) {
            return parse.getHost();
        }
        return parse.getHost() + URL_SPLIT + parse.getPort();
    }

    public String getDomainName() {
        String synGetGrsUrl = GrsApi.synGetGrsUrl(DNKeeperConfig.SERVICE_NAME_BACKUP, DNKeeperConfig.SERVICE_KEY);
        if (!TextUtils.isEmpty(synGetGrsUrl) && synGetGrsUrl.contains(URL_SPLIT)) {
            String[] split = synGetGrsUrl.split(URL_SPLIT);
            if (split.length == 3) {
                synGetGrsUrl = split[0] + URL_SPLIT + split[1];
                this.ip = split[2];
            }
        }
        if (TextUtils.isEmpty(getHost(synGetGrsUrl))) {
            if (this.preferences != null) {
                synGetGrsUrl = this.preferences.getString(DNKeeperConfig.DNKEEPER_SP);
            }
            if (TextUtils.isEmpty(getHost(synGetGrsUrl))) {
                synGetGrsUrl = defaultDomain;
            }
        }
        return getHost(synGetGrsUrl);
    }

    public void queryIpsAsync(RequestHost requestHost, DNSCallback dNSCallback) {
        if (dNSCallback != null) {
            this.taskExecutor.submit(new 2(this, dNSCallback, requestHost));
        }
    }

    public DnsResult queryIpsSync(RequestHost requestHost) {
        DnsResult dnsResult = new DnsResult();
        if (requestHost == null) {
            return dnsResult;
        }
        String domainName = requestHost.getDomainName();
        String domainName2 = getDomainName();
        if (TextUtils.isEmpty(domainName) || TextUtils.isEmpty(domainName2) || ContextUtil.getContext() == null) {
            return dnsResult;
        }
        DnsResult parseResponse;
        if (domainName.equals(domainName2)) {
            Logger.i(TAG, "domainName queryIps from SharePreference");
            if (this.preferences != null) {
                parseResponse = DNKeeperUtil.parseResponse(this.preferences.getString(domainName));
            } else {
                parseResponse = dnsResult;
            }
            if (DNKeeperUtil.isIpListEmpty(parseResponse)) {
                parseResponse = DNKeeperUtil.parseDnsResult(parseResponse, this.ip);
            }
            return parseResponse;
        }
        RequestRecord requestRecord = (RequestRecord) this.requestRecordHashMap.get(domainName);
        if (requestRecord != null) {
            dnsResult = requestRecord.getDnsResult();
            if (!DNKeeperUtil.isIpListEmpty(dnsResult)) {
                Logger.i(TAG, "queryIps from Map");
                if (!requestRecord.isNeedUpdate() || System.currentTimeMillis() - dnsResult.getCreateTime() <= 60000) {
                    return dnsResult;
                }
                Logger.i(TAG, "lazyUpdate domain: " + domainName);
                submitRequest(requestHost, domainName2);
                return dnsResult;
            }
        }
        Future submitRequest = submitRequest(requestHost, domainName2);
        if (submitRequest != null) {
            try {
                parseResponse = (DnsResult) submitRequest.get((long) this.timeout, TimeUnit.MILLISECONDS);
            } catch (Throwable e) {
                Logger.w(TAG, "queryIpsSync failed ", e);
                parseResponse = dnsResult;
            }
            if (!DNKeeperUtil.isIpListEmpty(parseResponse)) {
                Logger.i(TAG, "queryIps from dnkeeper service");
                return parseResponse;
            }
        }
        parseResponse = dnsResult;
        Logger.i(TAG, "queryIps from SharePreference");
        if (this.preferences != null) {
            parseResponse = DNKeeperUtil.parseResponse(this.preferences.getString(domainName));
        }
        return parseResponse;
    }

    public DnsResult queryIpsFromCache(String str) {
        DnsResult dnsResult = new DnsResult();
        if (TextUtils.isEmpty(str)) {
            Logger.v(TAG, "queryIpsFromCache domain is null");
            return dnsResult;
        }
        DnsResult dnsResult2;
        RequestRecord requestRecord = (RequestRecord) this.requestRecordHashMap.get(str);
        if (requestRecord != null) {
            dnsResult2 = requestRecord.getDnsResult();
        } else {
            dnsResult2 = dnsResult;
        }
        if (DNKeeperUtil.isIpListEmpty(dnsResult2)) {
            Logger.v(TAG, "no local data = %s", str);
        }
        return dnsResult2;
    }

    public boolean removeCache(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Logger.v(TAG, "removeCache host: " + str);
        RequestRecord requestRecord = (RequestRecord) this.requestRecordHashMap.get(str);
        if (requestRecord != null) {
            requestRecord.setNeedUpdate(true);
        }
        return true;
    }

    private Future submitRequest(RequestHost requestHost, String str) {
        RequestRecord requestRecord;
        String domainName = requestHost.getDomainName();
        synchronized (this.lock) {
            RequestRecord requestRecord2 = (RequestRecord) this.requestRecordHashMap.get(domainName);
            if (requestRecord2 == null) {
                requestRecord2 = new RequestRecord();
                this.requestRecordHashMap.put(domainName, requestRecord2);
                requestRecord = requestRecord2;
            } else {
                requestRecord = requestRecord2;
            }
        }
        Long valueOf = Long.valueOf(requestRecord.getRequestTime());
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - valueOf.longValue() < ((long) this.requestIntervalFailed)) {
            Logger.i(TAG, "now - time = " + (currentTimeMillis - valueOf.longValue()));
            return null;
        }
        Future future;
        synchronized (this.lock) {
            future = requestRecord.getFuture();
            if (future == null) {
                Logger.i(TAG, "future == null");
                future = this.taskExecutor.submit(new DNKeeperCallable(requestHost, str, requestRecord, this.preferences));
                requestRecord.setRequestTime(0);
                requestRecord.setFuture(future);
            }
            Logger.i(TAG, "future = " + future);
        }
        return future;
    }
}
